package com.QK.cnstudy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.QK.cnstudy.adapter.AnswerAdaper;
import com.QK.cnstudy.bean.Quiz;
import com.QK.cnstudy.bean.Subject;
import com.QK.cnstudy.db.DBManager;

public class SubjectActivity extends Activity implements OnItemClickListener, OnClickListener {

    public Activity activity;
    public int hintNum = 2;
    private DBManager dbManager;

    private Quiz quiz;

    private TextView stateTextView;
    private ListView subjectListView;
    private Button finishButton;
    private int currentSubjectIndex = 1;

    public final static int MSG_NEXTSUBJECT = 0;
    public final static int MSG_HINT = 1;
    // ///
    private AnswerAdaper adapter;
    private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_NEXTSUBJECT:
                int selected = checkSelected();
                if (selected != -1) {
                    quiz.getSubjects().get(currentSubjectIndex - 1).setSelectAnswer(selected);

                    if (currentSubjectIndex == quiz.getSubjectNum()) {
                        quiz.setTestSubjectNum(currentSubjectIndex);
                        gotoTestResultActivity();
                    } else {
                        currentSubjectIndex++;
                        setSubject(currentSubjectIndex);
                    }

                } else {
                    Toast.makeText(activity, "请选择答案", Toast.LENGTH_SHORT).show();
                }
                break;
            case MSG_HINT:
                if (hintNum == 0) {
                    Toast.makeText(activity, "没有提示机会了", Toast.LENGTH_SHORT).show();
                } else {
                    hintNum--;
                    Toast.makeText(activity,
                                    "答案是"
                                                    + ((char) (quiz.getSubjects().get(currentSubjectIndex - 1)
                                                                    .getAnswer() + 'A')), Toast.LENGTH_SHORT).show();
                    for (int i = list.size() - 1; i >= 0; i--) {
                        if ((Integer) list.get(i).get("flag") == AnswerAdaper.FLAG_NAVI) {
                            list.get(i).put("hintNum", hintNum);
                            break;
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
                break;
            }
        }
    };

    public int checkSelected() {
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            if ((Integer) map.get("flag") == AnswerAdaper.FLAG_ANSWER) {
                if ((Boolean) map.get("selected") == true) {
                    return (Integer) map.get("index");
                }
            }
        }
        return -1;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.subject);
        activity = this;
        dbManager = CnStudyApp.app.dbManager;
        getView();
        getQuiz();
        setSubject(currentSubjectIndex);

        finishButton.setOnClickListener(this);
    }

    public void setSubject(int index) {
        list.clear();

        String stateString = index + " / " + quiz.getSubjectNum();
        stateTextView.setText(stateString);
        Subject subject = quiz.getSubjects().get(index - 1);

        int sentenceId = subject.getSentenceId();
        String content = dbManager.getSentenceById(sentenceId).getContent();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("flag", AnswerAdaper.FLAG_TITLE);
        map.put("title", "(" + index + "/" + quiz.getSubjectNum() + ")" + content);
        list.add(map);
        for (int i = 0; i < subject.getAnswerIds().size(); i++) {
            int answerId = subject.getAnswerIds().get(i);
            String answerString = dbManager.getSentenceById(answerId).getTranslation();
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("flag", AnswerAdaper.FLAG_ANSWER);
            map2.put("title", "<font color='#63950c'>" + ((char) (i + 'A')) + ". </font>" + answerString);
            map2.put("selected", false);
            map2.put("index", i);
            list.add(map2);
        }
        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("flag", AnswerAdaper.FLAG_NAVI);
        map3.put("hintNum", hintNum);
        map3.put("next_subject", currentSubjectIndex != quiz.getSubjectNum());
        list.add(map3);

        adapter = new AnswerAdaper(this, list, mHandler);
        subjectListView.setAdapter(adapter);
        subjectListView.setOnItemClickListener(this);
    }

    public void getView() {
        stateTextView = (TextView) findViewById(R.id.state);
        subjectListView = (ListView) findViewById(R.id.subject_list);
        finishButton = (Button) findViewById(R.id.finish);
    }

    public void getQuiz() {
        Bundle bundle = getIntent().getExtras();
        quiz = (Quiz) bundle.getSerializable("quiz");
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Map<String, Object> map = list.get(arg2);
        int flag = (Integer) map.get("flag");
        if (flag != AnswerAdaper.FLAG_ANSWER)
            return;
        boolean selected = (Boolean) map.get("selected");
        if (!selected) {
            map.put("selected", true);
            for (int i = 0; i < list.size(); i++) {
                int flag2 = (Integer) list.get(i).get("flag");
                if (flag2 == AnswerAdaper.FLAG_ANSWER && i != arg2) {
                    list.get(i).put("selected", false);
                }
            }
            adapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.finish:
            int selectedIndex = checkSelected();
            if (selectedIndex != -1) {
                quiz.setTestSubjectNum(currentSubjectIndex);
                quiz.getSubjects().get(currentSubjectIndex - 1).setSelectAnswer(selectedIndex);
                gotoTestResultActivity();
            } else {
                Toast.makeText(this, "请选择答案", Toast.LENGTH_SHORT).show();
            }
            break;

        default:
            break;
        }
    }

    public void gotoTestResultActivity() {
        Intent intent = new Intent(this, ResultActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        Bundle bundle = new Bundle();
        bundle.putSerializable("quiz", quiz);
        intent.putExtras(bundle);
        startActivity(intent);
        this.finish();
    }
}
